package org.btik.light.nbi;

import com.google.gson.Gson;
import org.btik.light.meta.base.Command;
import org.btik.light.nbi.cmd.JsonCmd;
import org.btik.light.nbi.cmd.RawCommand;
import org.btik.light.tool.ByteUtil;

import java.nio.charset.StandardCharsets;

import static org.btik.light.nbi.NbiCmdParser.Constant.*;

/**
 * @author lustre
 * @since 2022/11/21 0:46
 * nbi 命令解析
 */
public class NbiCmdParser {
    interface Constant {
        byte[] HEAD = new byte[]{'L', 'N', 'B', 'I'};
        int HEAD_LEN = HEAD.length;

        int CMD_INDEX = HEAD_LEN + 1;

        int SN_INDEX = CMD_INDEX + 1;

        //### cmdType ###
        byte RAW = 0;
        byte JSON = 1;
        // ### ####

    }

    static Gson GSON = new Gson();

    public static Command parse(byte[] data, int length) {
        if (HEAD_LEN >= length) {
            return null;
        }
        if (!ByteUtil.equals(data, 0, HEAD, 0, HEAD_LEN)) {
            return null;
        }

        switch (data[HEAD_LEN]) {
            case RAW -> {
                int snLen = data[CMD_INDEX] & 0xff;
                String sn = new String(data, SN_INDEX, snLen);
                int len = length - SN_INDEX - snLen;
                byte[] bytes = new byte[len];
                System.arraycopy(data, SN_INDEX + snLen, bytes, 0, len);
                return RawCommand.of(sn, bytes);
            }
            case JSON -> {
                return parseJson(data, CMD_INDEX, length);
            }
        }

        return null;
    }

    public static Command parseJson(byte[] data, int offset, int length) {
        return GSON.fromJson(new String(data, offset, length - offset, StandardCharsets.UTF_8), JsonCmd.class);
    }

}
